package p2p.view.components
{
	import flash.display.DisplayObject;
	
	import mx.collections.ArrayCollection;
	import mx.containers.TitleWindow;
	import mx.core.FlexGlobals;
	import mx.events.CollectionEvent;
	import mx.managers.PopUpManager;
	
	import p2p.model.vo.DescriptorVO;
	
	public class FileSharingMonitorBase extends TitleWindow
	{
		
		[Bindable]
		protected  var filesDescriptors:ArrayCollection;
		
		
		public function FileSharingMonitorBase()
		{
			filesDescriptors = new ArrayCollection();
			filesDescriptors.addEventListener(CollectionEvent.COLLECTION_CHANGE, collectionChangeHandler);
		}
		
		
		public function add(fileDescriptor:DescriptorVO) : void
		{
			filesDescriptors.addItem(fileDescriptor);
		}
		
		public function remove(fileDescriptor:DescriptorVO) : int
		{
			var result:int = -1;
			for( var i:int = 0; i < filesDescriptors.length; i++ )
			{
				var descriptor:DescriptorVO = filesDescriptors[i] as DescriptorVO;
				if (fileDescriptor.id == descriptor.id)
				{
					filesDescriptors.removeItemAt(i);
					result = i;
					break;
				}
			}
			return result;
		}
		
		public function update(fileDescriptor:DescriptorVO) : void
		{
			var index:int = remove(fileDescriptor);
			index >= 0 ?
				filesDescriptors.addItemAt(fileDescriptor, index) :
				filesDescriptors.addItem(fileDescriptor);
		}
		
		private function collectionChangeHandler(event:CollectionEvent) : void
		{
			event.stopPropagation();
			if (filesDescriptors.length > 0 )
			{
				show();
			}
			else
			{
				hide();
			}

		}
		
		private function show() : void
		{
			if (!instance.isPopUp)
			{
				PopUpManager.addPopUp(instance, FlexGlobals.topLevelApplication as DisplayObject);
				PopUpManager.centerPopUp(instance);
			}
		}
		
		private function hide() : void
		{
			if (instance.isPopUp)
			{
				PopUpManager.removePopUp(instance);
			}
		}
		
		protected static var instance:FileSharingMonitorBase;
	}
}